<template>
  <view class="login-container">
    <!-- Logo区域 -->
    <view class="logo-section">
      <image class="logo" :src="globalConfig.appInfo.logo" mode="aspectFit"></image>
      <text class="title">若依移动端</text>
      <text class="subtitle">基于 Vue3 + TypeScript + Uniapp</text>
    </view>

    <!-- 登录表单 -->
    <view class="form-section">
      <!-- 用户名输入框 -->
      <view class="input-group">
        <view class="input-box">
          <text class="iconfont icon-user"></text>
          <input
            v-model="loginForm.username"
            class="input"
            type="text"
            placeholder="请输入账号"
            maxlength="30"
            placeholder-class="placeholder"
          />
        </view>
      </view>

      <!-- 密码输入框 -->
      <view class="input-group">
        <view class="input-box">
          <text class="iconfont icon-password"></text>
          <input
            v-model="loginForm.password"
            class="input"
            type="password"
            placeholder="请输入密码"
            maxlength="20"
            placeholder-class="placeholder"
          />
        </view>
      </view>

      <!-- 验证码输入框 -->
      <view class="input-group verify-group" v-if="captchaEnabled">
        <view class="input-box">
          <text class="iconfont icon-code"></text>
          <input
            v-model="loginForm.code"
            class="input"
            type="number"
            placeholder="请输入验证码"
            maxlength="4"
            placeholder-class="placeholder"
          />
        </view>
        <image class="verify-code" :src="codeUrl" @tap="getCode"></image>
      </view>

      <!-- 登录按钮 -->
      <button class="login-btn" @tap="handleLogin" :loading="loading">
        {{ loading ? '登录中...' : '登录' }}
      </button>

      <!-- 其他选项 -->
      <view class="options">
        <view class="register" v-if="register">
          <text class="text-grey">没有账号？</text>
          <text class="link" @tap="handleUserRegister">立即注册</text>
        </view>
      </view>
    </view>

    <!-- 底部协议 -->
    <view class="agreement">
      <text class="text-grey">登录即代表同意</text>
      <text class="link" @tap="handleUserAgrement">《用户协议》</text>
      <text class="text-grey">和</text>
      <text class="link" @tap="handlePrivacy">《隐私政策》</text>
    </view>
  </view>
</template>

<script>
import { getCodeImg } from '@/api/login'
import { useConfigStore, useUserStore } from '@/stores'
import { encrypt } from '@/utils/jsencrypt'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      loading: false,
      codeUrl: "",
      captchaEnabled: true,
      register: false,
      globalConfig: useConfigStore().config,
      loginForm: {
        username: "",
        password: "",
        code: "",
        uuid: ''
      }
    }
  },
  created() {
    this.getCode()
  },
  onLoad() {
    // 检查是否有有效的 token
    const token = getToken()
    if (token) {
      // 如果有 token，直接跳转到首页
      uni.reLaunch({
        url: '/pages/index'
      })
    }
  },
  methods: {
    // 用户注册
    handleUserRegister() {
      this.$tab.redirectTo(`/pages/register`)
    },
    // 隐私协议
    handlePrivacy() {
      let site = this.globalConfig.appInfo.agreements[0]
      this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
    },
    // 用户协议
    handleUserAgrement() {
      let site = this.globalConfig.appInfo.agreements[1]
      this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
    },
    // 获取图形验证码
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.data?.captchaEnabled ?? true
        if (this.captchaEnabled) {
          this.codeUrl = 'data:image/gif;base64,' + res.data.img
          this.loginForm.uuid = res.data.uuid
        }
      })
    },
    // 登录方法
    async handleLogin() {
      if (this.loading) return
      if (this.loginForm.username === "") {
        uni.showToast({ title: "请输入您的账号", icon: 'error' })
      } else if (this.loginForm.password === "") {
        uni.showToast({ title: "请输入您的密码", icon: 'error' })
      } else if (this.captchaEnabled && this.loginForm.code === "") {
        uni.showToast({ title: "请输入验证码", icon: 'error' })
      } else {
        this.loading = true
        try {
          await this.pwdLogin()
        } finally {
          this.loading = false
        }
      }
    },
    // 密码加密登录方法
    async pwdLogin() {
      const loginData = {
        ...this.loginForm,
        password: encrypt(this.loginForm.password)
      }

      useUserStore().Login(loginData).then((res) => {
        if (res?.code === 200) {
          uni.hideLoading()
          this.loginSuccess()
        }
      }).catch(() => {
        if (this.captchaEnabled) {
          this.getCode()
        }
      })
    },
    // 登录成功后，处理函数
    loginSuccess() {
      // 设置用户信息
      useUserStore().GetInfo().then(res => {
        if (res.code === 200) {
          uni.reLaunch({ url: '/pages/index' })
        }
      }).catch(err => {
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
      })
    }
  }
}
</script>

<style lang="scss">
page {
  background-color: #f5f7fa;
}

.login-container {
  min-height: 100vh;
  padding: 60rpx 40rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;

  .logo-section {
    margin-top: 60rpx;
    text-align: center;

    .logo {
      width: 160rpx;
      height: 160rpx;
      margin-bottom: 24rpx;
      border-radius: 20rpx;
    }

    .title {
      font-size: 44rpx;
      font-weight: 600;
      color: #2c3e50;
      margin-bottom: 16rpx;
      display: block;
    }

    .subtitle {
      font-size: 26rpx;
      color: #909399;
    }
  }

  .form-section {
    margin-top: 80rpx;

    .input-group {
      margin-bottom: 32rpx;

      .input-box {
        background-color: #fff;
        border-radius: 16rpx;
        height: 100rpx;
        display: flex;
        align-items: center;
        padding: 0 32rpx;
        box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);

        .iconfont {
          font-size: 40rpx;
          color: #909399;
          margin-right: 24rpx;
        }

        .input {
          flex: 1;
          height: 100%;
          font-size: 30rpx;
          color: #2c3e50;
        }

        .placeholder {
          color: #c0c4cc;
        }
      }
    }

    .verify-group {
      display: flex;
      gap: 24rpx;

      .input-box {
        flex: 1;
      }

      .verify-code {
        width: 200rpx;
        height: 100rpx;
        border-radius: 16rpx;
      }
    }

    .login-btn {
      margin-top: 48rpx;
      height: 100rpx;
      line-height: 100rpx;
      background-color: #409eff;
      color: #fff;
      font-size: 32rpx;
      font-weight: 500;
      border-radius: 50rpx;
      box-shadow: 0 8rpx 16rpx rgba(64,158,255,0.2);
      transition: all 0.3s;

      &:active {
        transform: scale(0.98);
        opacity: 0.9;
      }
    }

    .options {
      margin-top: 32rpx;
      text-align: center;

      .register {
        font-size: 28rpx;

        .text-grey {
          color: #909399;
        }

        .link {
          color: #409eff;
          margin-left: 8rpx;
        }
      }
    }
  }

  .agreement {
    margin-top: auto;
    text-align: center;
    font-size: 26rpx;
    padding: 40rpx 0;

    .text-grey {
      color: #909399;
    }

    .link {
      color: #409eff;
      margin: 0 8rpx;
    }
  }
}
</style>
